package com.zpz.framework.zpzoauth.config.oauth.authorization.exouath;

import com.zpz.framework.zpzoauth.common.encrypt.ZpzOauthSaltUtil;
import com.zpz.framework.zpzoauth.common.utils.ZpzOauthRequestUtil;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultMsg;
import com.zpz.framework.zpzoauth.common.result.ZpzOauthResultStatus;
import com.zpz.framework.zpzoauth.pojo.po.OauthClientDetails;
import com.zpz.framework.zpzoauth.config.oauth.authorization.exouath.authenticator.ZpzOauthIntegrationAuthenticator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * @author zhangpanzhi
 * @time 2019-07-09
 * @description 未经本人允许请勿随便改动，尊重劳动
 * */
@Component
public class ZpzOauthIntegrationAuthenticationFilter extends GenericFilterBean implements ApplicationContextAware {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ZpzOauthRequestUtil zpzOauthRequestUtil;
    private static final String AUTH_TYPE_PARM_NAME = "auth_type";

    private static final String OAUTH_TOKEN_URL = "/oauth/token";

    private Collection<ZpzOauthIntegrationAuthenticator> authenticators;

    private ApplicationContext applicationContext;

    private RequestMatcher requestMatcher;

    public ZpzOauthIntegrationAuthenticationFilter(){
        this.requestMatcher = new OrRequestMatcher(
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "GET"),
                new AntPathRequestMatcher(OAUTH_TOKEN_URL, "POST")
        );
    }
    private void basicResponse( HttpServletResponse response,Enum<?> resultStatus) throws Exception{
        ZpzOauthResultMsg<Object> objectResultMsg = ZpzOauthResultMsg.customResultStatus(resultStatus);
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), objectResultMsg);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(requestMatcher.matches(request)){
            String[] si = null;
            try {
                String authorization = request.getHeader("Authorization");
                byte[] bytes = Base64.decodeBase64(authorization.split(" ")[1]);
                String str = new String(bytes);
                si = str.split(":");
                if (si==null||si.length<=1){
                    log.info(ZpzOauthResultStatus.OAUTH_10003.getMessage());
                    basicResponse(response, ZpzOauthResultStatus.OAUTH_10003);
                    return;
                }
                OauthClientDetails client = zpzOauthRequestUtil.getClient(si[0]);
                if (client==null){
                    log.info(ZpzOauthResultStatus.OAUTH_10004.getMessage());
                    basicResponse(response, ZpzOauthResultStatus.OAUTH_10004);
                    return;
                }
            } catch (Exception e) {
                log.info(ZpzOauthResultStatus.OAUTH_10003.getMessage()+":"+e.getMessage());
                ZpzOauthResultMsg<Object> objectResultMsg = ZpzOauthResultMsg.customResultStatus(ZpzOauthResultStatus.OAUTH_10003,e.getMessage());
                response.setContentType("application/json;charset=UTF-8");
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), objectResultMsg);
                return;
            }
            //设置集成登录信息
            ZpzOauthIntegrationAuthentication integrationAuthentication = new ZpzOauthIntegrationAuthentication();
            integrationAuthentication.setAuthType(request.getParameter(AUTH_TYPE_PARM_NAME));
            integrationAuthentication.setAuthParameters(request.getParameterMap());
            integrationAuthentication.setClientId(si[0]);
            String client_source = request.getHeader("client_source");
            integrationAuthentication.setSource(client_source);
            // 1 登录注册模式 2 登录模式
            String login_mode = request.getHeader("login_mode");
            Integer _login_mode=2;
            if (StringUtils.isNotBlank(login_mode)){
                try {
                    _login_mode = Integer.parseInt(login_mode);
                } catch (NumberFormatException e) {
                }
            }
            integrationAuthentication.setLoginMode(_login_mode);
            ZpzOauthIntegrationAuthenticationContext.set(integrationAuthentication);
            try{
                //预处理
                this.prepare(integrationAuthentication);

                filterChain.doFilter(request,response);

                //后置处理
                this.complete(integrationAuthentication);
            }catch (Exception e) {
                log.info("：：：：：：：：登录过滤异常：：：：：：：：");
                log.error(e.getMessage(),e);
            }finally {
                ZpzOauthIntegrationAuthenticationContext.clear();
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }

    /**
     * 进行预处理
     * @param integrationAuthentication
     */
    private void prepare(ZpzOauthIntegrationAuthentication integrationAuthentication) {

        //延迟加载认证器
        if(this.authenticators == null){
            synchronized (this){
                Map<String, ZpzOauthIntegrationAuthenticator> integrationAuthenticatorMap = applicationContext.getBeansOfType(ZpzOauthIntegrationAuthenticator.class);
                if(integrationAuthenticatorMap != null){
                    this.authenticators = integrationAuthenticatorMap.values();
                }
            }
        }

        if(this.authenticators == null){
            this.authenticators = new ArrayList<>();
        }

        for (ZpzOauthIntegrationAuthenticator authenticator: authenticators) {
            if(authenticator.support(integrationAuthentication)){
                authenticator.prepare(integrationAuthentication);
            }
        }
    }

    /**
     * 后置处理
     * @param integrationAuthentication
     */
    private void complete(ZpzOauthIntegrationAuthentication integrationAuthentication){
        for (ZpzOauthIntegrationAuthenticator authenticator: authenticators) {
            if(authenticator.support(integrationAuthentication)){
                authenticator.complete(integrationAuthentication);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static void main(String[] args) {
        System.out.println(ZpzOauthSaltUtil.getPwd("zhy_ksh_wl_app_0u8ty4j7o"));
    }



}
